package com.finalterm.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.finalterm.common.exception.BusinessException;
import com.finalterm.common.utils.JwtUtils;
import com.finalterm.user.dto.UserLoginDTO;
import com.finalterm.user.dto.UserRegisterDTO;
import com.finalterm.user.entity.User;
import com.finalterm.user.mapper.UserMapper;
import com.finalterm.user.service.UserService;
import com.finalterm.user.vo.LoginVO;
import com.finalterm.user.vo.UserVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

/**
 * 用户服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    
    @Override
    public UserVO register(UserRegisterDTO registerDTO) {
        // 检查用户名是否已存在
        User existUser = getUserByUsername(registerDTO.getUsername());
        if (existUser != null) {
            throw new BusinessException("用户名已存在");
        }
        
        // 创建用户
        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);
        user.setPassword(DigestUtils.md5DigestAsHex(registerDTO.getPassword().getBytes()));
        user.setStatus(1);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        
        userMapper.insert(user);
        
        // 转换为VO
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        
        log.info("用户注册成功：{}", user.getUsername());
        return userVO;
    }
    
    @Override
    public LoginVO login(UserLoginDTO loginDTO) {
        // 查询用户
        User user = getUserByUsername(loginDTO.getUsername());
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 验证密码
        String encryptedPassword = DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes());
        if (!encryptedPassword.equals(user.getPassword())) {
            throw new BusinessException("密码错误");
        }
        
        // 检查用户状态
        if (user.getStatus() == 0) {
            throw new BusinessException("用户已被禁用");
        }
        
        // 生成JWT token
        String token = JwtUtils.generateToken(user.getId(), user.getUsername());

        // 转换为VO
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);

        log.info("用户登录成功：{}", user.getUsername());
        return new LoginVO(token, userVO);
    }
    
    @Override
    public UserVO getUserById(Long userId) {
        // 直接从数据库获取
        User user = userMapper.selectById(userId);

        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }
    
    @Override
    public User getUserByUsername(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        return userMapper.selectOne(wrapper);
    }
    
    @Override
    public boolean validateUser(Long userId) {
        try {
            UserVO user = getUserById(userId);
            return user != null && user.getStatus() == 1;
        } catch (Exception e) {
            log.error("验证用户失败：{}", e.getMessage());
            return false;
        }
    }
}
